<script>
/**
 * 子导航栏
 */
import useNavInfoStore from "@/stores/nav";
import {computed} from "vue";
import useRouterNameInfoStore from "@/stores/router-name";

export default {
  name: "SubChannelMenu",
  setup(){
    const navInfoStore = useNavInfoStore();
    const routerNameInfoStore =  useRouterNameInfoStore()
    const selectId = computed(()=>navInfoStore.selectId);
    return{
      routerNameInfoStore,
      navInfoStore,
      selectId
    }
  },

  data(){
    return{
      mSubSelectId: this.navInfoStore.subDefaultItem.id,
    }
  },


  watch:{
    // 如果selectId改变（第一nav），就初始化组件数据
    selectId(){
      this.initValue(this.$route)
    },

    // 监听第二nav选中的值，更新仓库的值(点击时优先进入)
    mSubSelectId(newValue){
      let nav = this.navInfoStore;
      let routerName = this.routerNameInfoStore;
      // 如果subSelectId和仓库中的选中id不相等，则修改选中id和选中项,相等就直接退出
      if(newValue !== nav.subSelectId) nav.setSubSelect(newValue);
      else return;
      // 如果跳转到默认页面，不添加subEnglishName属性
      if(newValue === nav.subDefaultItem.id){
        this.$router.push({
          name: routerName.channelVideo,
          params: {
            englishName: nav.selectItem.englishName,
            subEnglishName: nav.subDefaultItem.englishName
          }
        })
        return;
      }
      // 如果选中项为频道id，则路由跳到对应频道页面
      this.$router.push({
        name: routerName.channelVideo,
        params: {
          englishName: nav.selectItem.englishName,
          subEnglishName: nav.subSelectItem.englishName
        }
      })
    },


  },


  beforeRouteEnter(to) {
    console.log("进入路由: " + to.path);
  },

  beforeRouteUpdate(to){
    this.initValue(to);
  },


  methods:{
    // 根据to路由设置组件初始值
    initValue(route){
      let subEnglishName = route.params.subEnglishName;
      if(subEnglishName === '' || subEnglishName === undefined){

        this.mSubSelectId = this.navInfoStore.subDefaultItem.id;
      }else{
        this.navInfoStore.setSubSelectByName(subEnglishName);
        this.mSubSelectId = this.navInfoStore.subSelectId;
      }

    }
  }
}
</script>

<template>

<div>
  <div>
    <Nav :menu-value="this.navInfoStore.subMenus" v-model="mSubSelectId"></Nav>
  </div>
  {{ $route.params.englishName }}
  <router-view></router-view>
</div>
</template>

<style scoped>

</style>